import yaml
from configparser import ConfigParser


def get_config(filename, encoding='utf-8') -> dict:
    """
    获取配置文件
    :param filename:
    :param encoding:
    :return:
    """
    # 1.获取文件后缀名
    suffix = filename.split('.')[-1]

    # 2.判断这个配置文件的类型
    if suffix in ['ini', 'cfg', 'cnf']:
        # ini配置
        conf = ConfigParser()
        conf.read(filename, encoding=encoding)
        # 讲ini配置信息解析成一个大字典
        data = {}
        for section in conf.sections():
            data[section] = dict(conf.items(section))

    elif suffix in ['yml', 'yaml']:
        # yaml配置
        with open(filename, 'r', encoding=encoding) as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
    else:
        raise ValueError('不能识别的配置文件后缀')
    return data


if __name__ == '__main__':
    res = get_config('../config.ini')
    print(res)
    res = get_config('../config.yaml')
    print(res)
